import { Button, Drawer, message, Modal, ModalProps, Tag, Tooltip } from 'antd';
import QAView from './QAView';
import {
  BaseQuestionType,
  FaqDataset,
  FeedbackQuestionType,
  FreqQuestionType,
  QuestionType,
  SubQuestionType,
  UnknowQuestionType,
} from '@/types/know/know';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Ellipsis } from 'antd-mobile';
import datasetService from '@/api/services/datasetService';
import KnowMarkContextProvider, { KnowMarkContext } from '../context';
import { useContextSelector } from 'use-context-selector';
import { preprocessMarkdown } from '@/utils/regexRules';
import knowService from '@/api/services/knowService';
import { addTableHeader, removeThinkTags } from '@/utils/common';
import { CircleLoading } from '@/components/loading';
import { useUpdate } from 'ahooks';
import { useParams } from '@/router/hooks';
import Modals from '@/components/modals/Modals';
import ModalsFooterBtn from '@/components/modals/ModalsFooterBtn';
import React from 'react';
import Back from '@/components/router/Back';

interface Props extends ModalProps {
  type: QuestionType;
  data: BaseQuestionType | UnknowQuestionType | FeedbackQuestionType | FreqQuestionType;
  refresh: () => void;
  onCancel: () => void;
  completed?: (
    data: BaseQuestionType | UnknowQuestionType | FeedbackQuestionType | FreqQuestionType,
  ) => void;
}

const MarkModal = ({ data, open, type, refresh, onCancel, completed, ...props }: Props) => {
  const [selectedQA, setSelectedQA] = useState<SubQuestionType>(data?.questionList?.[0]! ?? null);
  const [loading, setLoading] = useState(false);
  const [questionLoading, setQuestionLoading] = useState(false);
  const [step, setStep] = useState(0);
  const { selectedDataset, answer, question, setAnswer } = useContextSelector(
    KnowMarkContext,
    (s) => s,
  );
  const update = useUpdate();

  const { appId = '' } = useParams() as { appId: string };

  const hasQuestionList = useMemo(() => {
    setSelectedQA(data?.questionList?.[0]!);
    return data && 'questionList' in data;
  }, [data?.questionList]);

  const onQAChange = (qa: SubQuestionType) => {
    setStep(0);
    setSelectedQA(qa);
  };

  const onConfirm = () => {
    if (data) {
      const noEditQuestions = data.questionList?.filter((item) => item.status === 0);
      if (noEditQuestions && noEditQuestions?.length > 0) {
        message.warning('存在未处理问题');
      } else {
        onCancel && onCancel();
      }
    }
  };

  const onCompleted = () => {
    if (data && data.questionList) {
      const noEditQuestions = data.questionList?.filter((item) => item.status === 0);
      if (noEditQuestions && noEditQuestions?.length == 0) {
        completed && completed(data);
      }
    } else if (data.status !== 0) {
      completed && completed(data);
    }
  };

  const onUpdateQA = async () => {
    try {
      const questionId = type === QuestionType.Feedback ? data?.annoId : selectedQA?.annoId;
      setLoading(true);
      if (!questionId) {
        message.info('该问答已发布，暂不支持修改！');
        return;
      }
      await knowService.updateMarkQuestion(questionId!, {
        q: question,
        a: answer,
      });

      if (type === QuestionType.Feedback) {
        data.status = 1;
        data.annoQ = question;
        data.annoA = answer;
        onCancel && onCancel();
      } else {
        selectedQA.status = 1;
        selectedQA.annoQ = question;
        selectedQA.annoA = answer;
      }
      onCompleted();
      refresh();
      message.success('更新成功');
      setStep(0);
      // onCancel && onCancel();
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const onInsertQA = async () => {
    if (selectedDataset === null) {
      return;
    }
    try {
      const questionId =
        type === QuestionType.Feedback ? data?.keyQuestionId : selectedQA?.questionId;
      setLoading(true);
      const res = await knowService.postMarkQuestion({
        id: data._id,
        appId,
        collection_id: selectedDataset?.children[0].collectionId,
        datas: [
          {
            q: question,
            a: answer,
            question_id: questionId,
          },
        ],
        type: type,
      });

      const resItem = res.find((item) => item.question_id === questionId);
      if (!resItem) {
        message.error('插入失败！');
        return;
      }

      // 根据detail接口结果更新问题状态，默认已标注
      const detail =
        type === QuestionType.Feedback
          ? await knowService.getFeedbackQuestionDetail(data?.keyQuestionId)
          : type === QuestionType.Frequent
          ? await knowService.getFrequentQuestionDetail(data?._id)
          : await knowService.getUnknownQuestionDetail(data?._id);

      const status =
        detail?.questionList?.find((item) => item?.questionId === questionId)?.status || 1;

      if (type === QuestionType.Feedback) {
        data.status = status;
        data.annoId = resItem.annoId;
        data.annoQ = question;
        data.annoA = answer;
        onCancel && onCancel();
        completed && completed(data);
      } else {
        selectedQA.status = status;
        selectedQA.annoId = resItem.annoId;
        selectedQA.annoQ = question;
        selectedQA.annoA = answer;
      }
      onCompleted();
      refresh();
      message.success('标注成功');
      setStep(0);
      // onCancel && onCancel();
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const onIgnore = async () => {
    try {
      setLoading(true);
      await knowService.postMarkQuestion({
        id: data?._id,
        appId,
        datas: [
          {
            q: type === QuestionType.Feedback ? data?.keyQuestionText : selectedQA?.text,
            a: type === QuestionType.Feedback ? data?.keyQuestionAnswer : selectedQA?.answer,
            question_id:
              type === QuestionType.Feedback ? data?.keyQuestionId : selectedQA?.questionId,
          },
        ],
        is_ignore: true,
        type: type,
      });
      if (selectedQA) {
        selectedQA.status = 2;
      } else {
        data.status = 2;
        onCancel && onCancel();
      }
      onCompleted();
      refresh();
      message.success('忽略成功');
      setStep(0);
      // onCancel && onCancel();
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const getTag = (status: number) => {
    switch (status) {
      case 0:
        return <Tag color="#A5A9BB">待处理</Tag>;
      case 1:
        return <Tag color="green">已标注</Tag>;
      case 2:
        return <Tag color="#2db7f5">已忽略</Tag>;
      case 3:
        return <Tag color="#2db7f5">待发布</Tag>;
      case 4:
        return <Tag color="#2db7f5">已发布</Tag>;
      default:
        return <Tag color="#A5A9BB">待处理</Tag>;
    }
  };

  const getTitle = () => {
    if (type === QuestionType.Feedback) {
      return '点踩问题';
    }
    if (type === QuestionType.Frequent) {
      return '高频问题';
    }
    return '未知问题';
  };

  const rewriteAnswer = (answer: string) => {
    if (!answer) {
      return '';
    }
    try {
      const a = addTableHeader(removeThinkTags(preprocessMarkdown(answer)));
      return a;
    } catch (error) {
      console.error(error);
      return '';
    }
  };

  useEffect(() => {
    setStep(0);
  }, [open]);

  const getQuestions = async () => {
    try {
      if (!open) {
        return;
      }

      if (data.questionList?.length == 0) {
        setQuestionLoading(true);
      }

      const res =
        type === QuestionType.Feedback
          ? await knowService.getFeedbackQuestionDetail(data?.keyQuestionId)
          : type === QuestionType.Frequent
          ? await knowService.getFrequentQuestionDetail(data?._id)
          : await knowService.getUnknownQuestionDetail(data?._id);

      data.questionList = res.questionList;
      data.qaList = res.qaList;
      data.roleName = res.roleName;
      data.keyQuestionAnswer = res.keyQuestionAnswer;
      setAnswer(res.keyQuestionAnswer);
      update();
    } catch (error) {
      console.error(error);
    } finally {
      setQuestionLoading(false);
    }
  };

  useEffect(() => {
    if (data) {
      getQuestions();
    }
  }, [data]);

  // return (
  //   <Modal
  //     open={open}
  //     onCancel={onCancel}
  //     destroyOnClose
  //     {...props}
  //     footer={null}
  //     // height={'100%'}
  //     style={{ maxWidth: '90%', minWidth: '70%', height: '80%' }}
  //     // 控制内容的滚动
  //     className="h-full overflow-hidden"
  //   >
  //     <div
  //       className="flex h-full flex-col overflow-hidden"
  //       style={{ height: 'calc(75vh - 220px)' }}
  //     >
  //       <div className="flex h-full flex-1 overflow-hidden">
  //         {hasQuestionList && (
  //           <div className="mr-2 flex w-1/4 flex-col overflow-hidden">
  //             <Tooltip
  //               title={
  //                 <div style={{ maxHeight: '200px', whiteSpace: 'pre-wrap', overflow: 'auto' }}>
  //                   {data?.keyQuestionText}
  //                 </div>
  //               }
  //               placement="top"
  //             >
  //               {''}
  //               <Ellipsis content={data?.keyQuestionText} rows={2} />
  //             </Tooltip>
  //             <div className="mt-2 flex">
  //               <Tag color="#FFE0E1">
  //                 <span className="text-black">{getTitle()}</span>
  //               </Tag>
  //               <div className="text-[#8C8C8C]">
  //                 <span>相关问题</span>
  //                 <span className="ml-2">{data?.questionList?.length}</span>
  //               </div>
  //             </div>
  //             <div className="mb-2 mt-4">相关问题</div>
  //             <div className="h-full flex-1 overflow-y-auto">
  //               <div className="mt-2 flex flex-grow flex-col">
  //                 {data?.questionList?.map((item) => {
  //                   return (
  //                     <div
  //                       key={item.questionId}
  //                       className="flex cursor-pointer items-center border-t-2 border-gray-200"
  //                       onClick={() => onQAChange(item)}
  //                     >
  //                       <Tooltip
  //                         title={
  //                           <div
  //                             style={{
  //                               maxHeight: '200px',
  //                               whiteSpace: 'pre-wrap',
  //                               overflow: 'auto',
  //                             }}
  //                           >
  //                             {item.text}
  //                           </div>
  //                         }
  //                         placement="top"
  //                       >
  //                         <div
  //                           className={`tetx-nowrap truncate  p-2 ${
  //                             selectedQA?.questionId === item.questionId
  //                               ? 'text-primary'
  //                               : 'text-[#8C8C8C]'
  //                           }`}
  //                         >
  //                           {item.text}
  //                         </div>
  //                       </Tooltip>

  //                       <div className="ml-auto">{getTag(item.status)}</div>
  //                     </div>
  //                   );
  //                 })}
  //               </div>
  //             </div>
  //           </div>
  //         )}
  //         <div className="h-full flex-1">
  //           <QAView
  //             onIgnore={onIgnore}
  //             onCancel={onCancel}
  //             step={step}
  //             status={type === QuestionType.Feedback ? data?.status : selectedQA?.status}
  //             setStep={setStep}
  //             q={type === QuestionType.Feedback ? data?.keyQuestionText : selectedQA?.text}
  //             a={rewriteAnswer(
  //               type === QuestionType.Feedback ? data?.keyQuestionAnswer : selectedQA?.answer,
  //             )}
  //             data={type === QuestionType.Feedback ? data : selectedQA}
  //           />
  //         </div>
  //       </div>
  //       <div className="mt-4 flex items-center justify-center">
  //         {/* {step === 0 && (
  //           <div className="flex gap-4">
  //             <Button type="primary" onClick={onConfirm}>
  //               完成
  //             </Button>
  //           </div>
  //         )} */}
  //         {step === 1 && (
  //           <div className="flex gap-4">
  //             <Button
  //               onClick={() => {
  //                 setStep(0);
  //               }}
  //             >
  //               取消
  //             </Button>
  //             {(type === QuestionType.Feedback ? data?.status : selectedQA?.status) === 0 && (
  //               <Button
  //                 type="primary"
  //                 onClick={() => {
  //                   setStep(2);
  //                 }}
  //               >
  //                 下一步
  //               </Button>
  //             )}
  //             {(type === QuestionType.Feedback ? data?.status : selectedQA?.status) !== 0 && (
  //               <Button
  //                 type="primary"
  //                 onClick={() => {
  //                   onUpdateQA();
  //                 }}
  //               >
  //                 修改
  //               </Button>
  //             )}
  //           </div>
  //         )}
  //         {step === 2 && (
  //           <div className="flex gap-4">
  //             <Button
  //               onClick={() => {
  //                 setStep(0);
  //               }}
  //             >
  //               取消
  //             </Button>
  //             <Button loading={loading} type="primary" onClick={onInsertQA}>
  //               入库
  //             </Button>
  //           </div>
  //         )}
  //       </div>
  //     </div>
  //     {questionLoading && (
  //       <div className="absolute left-0 top-0 h-full w-full rounded-xl bg-black opacity-20">
  //         <CircleLoading />
  //       </div>
  //     )}
  //   </Modal>
  // );

  const ModalsFooter = () => {
    return (
      <div
        className="flex items-center justify-center py-3"
        style={{
          borderTop: '1px solid #E5E6EB',
        }}
      >
        {/* {step === 0 && (
            <div className="flex gap-4">
              <Button type="primary" onClick={onConfirm}>
                完成
              </Button>
            </div>
          )} */}
        {step === 1 && (
          <div className="flex gap-3">
            <ModalsFooterBtn
              onClick={() => {
                setStep(0);
              }}
            >
              取消
            </ModalsFooterBtn>
            {(type === QuestionType.Feedback ? data?.status : selectedQA?.status) === 0 && (
              <ModalsFooterBtn
                type="primary"
                onClick={() => {
                  setStep(2);
                }}
              >
                下一步
              </ModalsFooterBtn>
            )}
            {(type === QuestionType.Feedback ? data?.status : selectedQA?.status) !== 0 && (
              <ModalsFooterBtn
                type="primary"
                onClick={() => {
                  onUpdateQA();
                }}
              >
                修改
              </ModalsFooterBtn>
            )}
          </div>
        )}
        {step === 2 && (
          <div className="flex gap-3">
            <ModalsFooterBtn
              onClick={() => {
                setStep(0);
              }}
            >
              取消
            </ModalsFooterBtn>
            <ModalsFooterBtn loading={loading} type="primary" onClick={onInsertQA}>
              入库
            </ModalsFooterBtn>
          </div>
        )}
      </div>
    );
  };

  const childRef = useRef<{ onEdit: () => void; testResult: () => void }>();

  const ModalsHeader = () => {
    const status = type === QuestionType.Feedback ? data?.status : selectedQA?.status;
    if (step === 0 && status !== 4 && status !== 2) {
      return (
        <div className="flex items-center gap-2">
          <span>你可以选择</span>
          {
            <Button
              onClick={() => {
                childRef.current?.onEdit();
              }}
            >
              {status !== 0 ? '修改' : '编辑'}预期问答
            </Button>
          }

          {status === 0 && (
            <React.Fragment>
              <span>或者</span>
              <p className="cursor-pointer underline" onClick={onIgnore}>
                忽略该问题，无需标注答案
              </p>
            </React.Fragment>
          )}
          <Button
            className="ml-auto mr-8"
            onClick={() => {
              childRef.current?.testResult();
              // setTestDrawer(true);
            }}
          >
            测试效果
          </Button>
        </div>
      );
    }

    if (step === 1) {
      return (
        <Back onClick={() => setStep(0)} title={`${status !== 0 ? '修改' : '编辑'}预期问答`} />
      );
    }

    if (step === 2) {
      return <Back onClick={() => setStep(1)} title="选择存放位置" />;
    }
  };

  return (
    <Modals
      open={open}
      onCancel={onCancel}
      // style={{ maxWidth: '90%', minWidth: '70%', height: '80%' }}
      width={1280}
      footer={step === 0 ? null : <ModalsFooter />}
      title={<ModalsHeader />}
      // okText={step === 1 ? '下一步' : '入库'}
    >
      <div className="flex h-[600px] flex-1 overflow-hidden">
        {/* <div className="flex h-full flex-1 overflow-hidden"> */}
        {hasQuestionList && (
          <div className="mr-2 flex w-1/4 flex-col overflow-hidden">
            <Tooltip
              title={
                <div style={{ maxHeight: '200px', whiteSpace: 'pre-wrap', overflow: 'auto' }}>
                  {data?.keyQuestionText}
                </div>
              }
              placement="top"
            >
              {''}
              <Ellipsis content={data?.keyQuestionText} rows={2} />
            </Tooltip>
            <div className="mt-2 flex">
              <Tag color="#FFE0E1">
                <span className="text-black">{getTitle()}</span>
              </Tag>
              <div className="text-[#8C8C8C]">
                <span>相关问题</span>
                <span className="ml-2">{data?.questionList?.length}</span>
              </div>
            </div>
            <div className="mb-2 mt-4">相关问题</div>
            <div className="h-full flex-1 overflow-y-auto">
              <div className="mt-2 flex flex-grow flex-col">
                {data?.questionList?.map((item) => {
                  return (
                    <div
                      key={item.questionId}
                      className="flex cursor-pointer items-center border-t-2 border-gray-200"
                      onClick={() => onQAChange(item)}
                    >
                      <Tooltip
                        title={
                          <div
                            style={{
                              maxHeight: '200px',
                              whiteSpace: 'pre-wrap',
                              overflow: 'auto',
                            }}
                          >
                            {item.text}
                          </div>
                        }
                        placement="top"
                      >
                        <div
                          className={`tetx-nowrap truncate  p-2 ${
                            selectedQA?.questionId === item.questionId
                              ? 'text-primary'
                              : 'text-[#8C8C8C]'
                          }`}
                        >
                          {item.text}
                        </div>
                      </Tooltip>

                      <div className="ml-auto">{getTag(item.status)}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}
        <div className="h-full flex-1">
          <QAView
            onIgnore={onIgnore}
            onCancel={onCancel}
            step={step}
            status={type === QuestionType.Feedback ? data?.status : selectedQA?.status}
            setStep={setStep}
            q={type === QuestionType.Feedback ? data?.keyQuestionText : selectedQA?.text}
            a={rewriteAnswer(
              type === QuestionType.Feedback ? data?.keyQuestionAnswer : selectedQA?.answer,
            )}
            data={type === QuestionType.Feedback ? data : selectedQA}
            ref={childRef}
          />
        </div>
      </div>
    </Modals>
  );
};

function RenderRoleMarkModal({ data, open, type, refresh, onCancel, completed, ...props }: Props) {
  return (
    <KnowMarkContextProvider>
      <MarkModal
        data={data}
        open={open}
        type={type}
        refresh={refresh}
        onCancel={onCancel}
        completed={completed}
        {...props}
      />
    </KnowMarkContextProvider>
  );
}

export default RenderRoleMarkModal;
